package LogicSide;

import java.sql.SQLException;

import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

import com.sun.org.apache.bcel.internal.generic.Select;

import DBside.JDBCConnection;
import DBside.Tools;

public class Login {
/**
 * 
 * @param user_name
 * @param password
 * @return session with message for errors, or session with empty message and jdbcconnection and user id of the user logged in
 * @throws Exception 
 */
	public static Session executeLogin(String user_name,String password) throws Exception
	{
		Session s=new Session();
		JDBCConnection con = new JDBCConnection();
		con.openConnection(Tools.getHomeURL(), Tools.getUserName(), Tools.getPassword()); //TODO: empty connection
		DBside.TableItem[] tiarr=new DBside.TableItem[1];
		tiarr[0]=new DBside.TableItem("name", Tools.Type.VARCHAR, user_name);
		java.sql.ResultSet user_query_result=con.select("id, password",tiarr,null,null,JDBCConnection.Table.USER);
		if(Tools.isEmpty(user_query_result))
		{
			s.setMsg("Error: username does not exist");
			return s;
		}
		user_query_result.next();
		String real_pass=user_query_result.getString("password");
		if(!real_pass.equals(password))
		{
			s.setMsg("Error: wrong password");
			return s;
		}
		s.setCon(con);
		s.setUser_id(user_query_result.getInt("id"));
		return s;
	}
}
